import { useState, useImperativeHandle, forwardRef, createRef, useCallback } from "react";

function App04() {
	const ref = createRef();
	const ChildWithRef = forwardRef(Child, ref);
	const onClick = () => {
		console.log(ref);
		console.log(ref.current.content);
		console.log(ref.current.input.current.value);
		console.log(ref.current.getValue());
	};
	return (
		<div className="App">
			<div>这是第四种用法：使用forwardRef+useImperativeHandle暴露函数子组件的属性，方法或ref</div>
			<ChildWithRef ref={ref} />
			<button onClick={onClick}>请点击 查看console</button>
		</div>
	);
}

const Child = (props, ref) => {
	const inputRef = createRef();
	const [content, setContent] = useState("");
	const onChange = useCallback((e) => {
		setContent(e.target.value);
	}, []);

	const getValue = useCallback(() => {
		return "this is from a func:" + content;
	}, [content]);

	useImperativeHandle(ref, () => ({
		content,
		input: inputRef,
		getValue,
	}));
	return <input value={content} ref={inputRef} onChange={onChange} />;
};

export default App04;
